//
//  BXPersonDataTagTypeVC.m
//  BXlive
//
//  Created by mac on 2020/8/26.
//  Copyright © 2020 cat. All rights reserved.
//

#import "BXPersonDataTagTypeVC.h"
#import "AddHuaTiCell.h"
#import "BXPersonFlowLayout.h"
#import "BXDynTopicSearchCell.h"
#import "BXDynTopicDelItemCell.h"
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <Masonry/Masonry.h>
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <YYCategories/YYCategories.h>

@interface BXPersonDataTagTypeVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic , strong) UIView * navView;
@property (strong, nonatomic) UIButton *backBtn;
@property (strong, nonatomic) UIButton *issueBtn;
@property (strong, nonatomic)UILabel *headerTitleLabel;
@property(nonatomic, strong)UICollectionView *collectionView;

@property(nonatomic, strong)NSMutableArray *AllTagArray;
@end

@implementation BXPersonDataTagTypeVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavView];
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
//    self.selArray = [NSMutableArray array];
    self.AllTagArray = [NSMutableArray array];
    
//    初始化列表视图
    BXPersonFlowLayout *layout = [[BXPersonFlowLayout alloc] init];
    layout.cellType = AlignWithLeft;
    layout.betweenOfCell = 12;
    //     layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.backgroundColor = [UIColor clearColor];
    
    [self.collectionView registerClass:[BXDynTopicDelItemCell class] forCellWithReuseIdentifier:@"cell1"];
    [self.collectionView registerClass:[BXDynTopicSearchCell class] forCellWithReuseIdentifier:@"cell2"];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    

    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerview"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footview"];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navView.mas_bottom).offset(10);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-__kBottomAddHeight);
    }];
    [self getData];
    [self getMyTag];
        
}
-(void)setNavView{
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64+__kTopAddHeight)];
    self.navView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.navView];
    
   UILabel *_viewTitlelabel = [[UILabel alloc]init];
    _viewTitlelabel.text = NSLocalizedString(@"同类标签", nil);
    _viewTitlelabel.textColor = sl_blackBGColors;
    _viewTitlelabel.textAlignment = 1;
    _viewTitlelabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
    [_navView addSubview:_viewTitlelabel];
    
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backBtn setImage:CImage(@"nav_icon_back_black") forState:BtnNormal];
    _backBtn.contentMode = UIViewContentModeScaleAspectFit;
    [_backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:_backBtn];

    _issueBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_issueBtn setImage:CImage(@"nav_icon_news_black") forState:BtnNormal];
    [_issueBtn setTitle:NSLocalizedString(@"保存", nil) forState:UIControlStateNormal];
    [_issueBtn setTitleColor:sl_textSubColors forState:UIControlStateNormal];
    _issueBtn.backgroundColor = sl_subBGColors;
    _issueBtn.userInteractionEnabled = NO;
    _issueBtn.titleLabel.font = SLPFFont(__ScaleWidth(14));
//    [_issueBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    _issueBtn.backgroundColor = sl_normalColors;
    _issueBtn.layer.cornerRadius = 13;
    _issueBtn.layer.masksToBounds = YES;
    _issueBtn.contentMode = UIViewContentModeScaleAspectFit;
    [self.navView addSubview:_issueBtn];
    [_issueBtn addTarget:self action:@selector(AddClick) forControlEvents:UIControlEventTouchUpInside];
    
    [_viewTitlelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_navView);
        make.width.mas_equalTo(__ScaleWidth(72/4*6));
        make.height.mas_equalTo(25);
        make.centerY.equalTo(_navView.mas_bottom).offset(-22);
    }];
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(__ScaleWidth(12));
        make.width.height.mas_equalTo(18.5);
        make.top.mas_equalTo(20 + __kTopAddHeight + 12);
    }];
    [_issueBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-12);
        make.width.mas_equalTo(52);
        make.height.mas_equalTo(26);
        make.top.mas_equalTo(20 + __kTopAddHeight + 12);
    }];
    

}

-(void)AddClick{
    [self SaveMyTag];
}
-(void)backClick{
    [self pop];
}
-(void)getData{
    [BGProgressHUD showLoadingAnimation];
    [NewHttpManager GetAllImpressionSuccess:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
        [BGProgressHUD hidden];
        if (flag) {
            NSArray *array = jsonDic[@"data"];
            if (array && [array isArray]) {
                self.AllTagArray = [NSMutableArray arrayWithArray:array];
                [self.collectionView reloadData];
            }
        }else{
            [BGProgressHUD showInfoWithMessage:jsonDic[@"msg"]];
        }
    } failure:^(NSError *error) {
        [BGProgressHUD hidden];
    }];
}
-(void)getMyTag{
    [NewHttpManager GetuserImpressionSuccess:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
        
        if (flag) {
            NSArray *array = jsonDic[@"data"];
            if (array && [array isArray]) {
                self.selArray = [NSMutableArray arrayWithArray:array];
                [self.collectionView reloadData];
            }
        }else{
            [BGProgressHUD showInfoWithMessage:jsonDic[@"msg"]];
        }
    } failure:^(NSError *error) {
        [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"获取数据失败", nil)];
    }];
}
-(void)SaveMyTag{
    
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *impStrArr = [NSMutableArray new];
    for (NSDictionary *dic in self.selArray) {
        [array addObject:dic[@"id"]];
        [impStrArr addObject:dic[@"name"]];
    }
    WS(weakSelf);
    NSString *ids = [array componentsJoinedByString:@","];
    if (IsNilString(ids)) {
        ids = @"";
    }
    [NewHttpManager SaveUserIpmpressWithids:ids success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
        if (flag) {
//            保存成功
            BXLiveUser *lu = [BXLiveUser currentBXLiveUser];
            lu.impression = [impStrArr componentsJoinedByString:@","];
            [BXLiveUser setCurrentBXLiveUser:lu];
            
            [SLProgressHUD slShowInfoWithMessage:NSLocalizedString(@"保存成功", nil)];
            if (weakSelf.complateBlock) {
                weakSelf.complateBlock(lu.impression);
            }
            [weakSelf pop];
            
        }else{
            [BGProgressHUD showInfoWithMessage:jsonDic[@"msg"]];
        }
    } failure:^(NSError *error) {
        [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"操作失败", nil)];
    }];
}
#pragma mark - UICollectionViewDelegate/Datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        if (_selArray.count == 0) {
            return 1;
        }
        return _selArray.count;
    }
    if (section == 1) {
        return _AllTagArray.count;
    }
  return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        BXDynTopicDelItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell1" forIndexPath:indexPath];
        WS(weakSelf);
        cell.DidDelIndex = ^{
            [weakSelf.selArray removeObjectAtIndex:indexPath.row];
            [weakSelf.collectionView reloadData];
            [weakSelf.issueBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            weakSelf.issueBtn.backgroundColor = sl_normalColors;
            weakSelf.issueBtn.userInteractionEnabled = YES;
        };
        cell.StrType = @"tag";
        if (_selArray.count == 0) {
            cell.topicStr = NSLocalizedString(@"你还没有标签哦", nil);
            cell.concentLabel.backgroundColor = [UIColor whiteColor];
            cell.concentLabel.font = SLPFFont(12);
            cell.concentLabel.textColor = UIColorHex(#B2B2B2);
            cell.button.hidden = YES;
        }else{
            cell.button.hidden = NO;
            cell.topicStr = [self.selArray[indexPath.row] objectForKey:@"name"];
            cell.concentLabel.backgroundColor = sl_subBGColors;
            cell.concentLabel.font = SLBFont(12);
            cell.concentLabel.textColor = UIColorHex([self.selArray[indexPath.row] objectForKey:@"color"]);
        }
        return cell;
    }else{
    BXDynTopicSearchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell2" forIndexPath:indexPath];
        cell.StrType = @"tag";
        cell.topicStr = [self.AllTagArray[indexPath.row] objectForKey:@"name"];
    return cell;
    }

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
    }
    if (indexPath.section == 1) {
        if (_selArray.count >= 6) {
            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"只能选择6个标签哦", nil)];
            return;
        }
        NSString *indexid = [NSString stringWithFormat:@"%@",[self.AllTagArray[indexPath.row] objectForKey:@"id"]];
        for (int i = 0; i< self.selArray.count; i++) {
            NSString *selid = [NSString stringWithFormat:@"%@",[self.selArray[i] objectForKey:@"id"]];
            if ([selid isEqualToString:indexid]) {
                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"你已经添加过此标签了哦", nil)];
                return;
            }
        }
        [_issueBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _issueBtn.backgroundColor = sl_normalColors;
        _issueBtn.userInteractionEnabled = YES;
        [self.selArray addObject:self.AllTagArray[indexPath.row]];
        [self.collectionView reloadData];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 1) {
        NSString *str = [self.AllTagArray[indexPath.row] objectForKey:@"name"];
        CGFloat width = [str widthForFont:[UIFont fontWithName:@"PingFangSC-Semibold" size:12]];
        CGFloat height = 0;
        if (width > 300) {
            width = 300;
            height = [str heightForFont:[UIFont fontWithName:@"PingFangSC-Semibold" size:12] width:300];
            return CGSizeMake(width + 40, height + 15);
        }
        return CGSizeMake(width + 40, 38);
    }else{
        NSString *str = @"";
        if (self.selArray.count == 0) {
            str = NSLocalizedString(@"你还没有标签哦", nil);
        }else{
            str = [self.selArray[indexPath.row] objectForKey:@"name"];
        }
        CGFloat width = [str widthForFont:[UIFont fontWithName:@"PingFangSC-Semibold" size:12]];
        CGFloat height = 0;
        if (width > 300) {
            width = 300;
            height = [str heightForFont:[UIFont fontWithName:@"PingFangSC-Semibold" size:12] width:300];
            return CGSizeMake(width + 40, height + 15);
        }
        return CGSizeMake(width + 40, 38);
    }

}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 12;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 12;
}


//定义每个Section的四边间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {

    return UIEdgeInsetsMake(12, 12, 10, 12);
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {

        if (indexPath.section == 0) {
            UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerview" forIndexPath:indexPath];
            if (_headerTitleLabel) {
                [_headerTitleLabel removeFromSuperview];
            }
            _headerTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 5, 200, 30)];
            _headerTitleLabel.text = [NSString stringWithFormat:NSLocalizedString(@"已选择标签(%lu/6)", nil), (unsigned long)self.selArray.count];
            _headerTitleLabel.textAlignment = 0;
            _headerTitleLabel.textColor = [UIColor blackColor];
            _headerTitleLabel.font = SLBFont(16);
            [headView addSubview:_headerTitleLabel];
            return headView;
        }else{
            return nil;
        }
    }
    if([kind isEqualToString:UICollectionElementKindSectionFooter])
    {

        if (indexPath.section == 0) {
            UICollectionReusableView *headView1 = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footview" forIndexPath:indexPath];
            UILabel *footlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, headView1.frame.size.width, 10)];
            footlabel.backgroundColor = [UIColor colorWithRed:0.96 green:0.97 blue:0.99 alpha:1.00];
            [headView1 addSubview:footlabel];
            return headView1;
        }else{
            return nil;
        }
    }
    
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"UICollectionReusableView" forIndexPath:indexPath];
    return headView;

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, 40);
    }
    return CGSizeMake(0, 0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, 10);
    }
    return CGSizeMake(0, 0);
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
